<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
       <el-table-column label="营养成分" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.name`" :rules="formRules.name" class="mb-0px!">
            <select-milk-attribute-com v-model="row.name" @select="onSelectAttribute($event, row)"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="每100g含量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.per100g`" :rules="formRules.per100g" class="mb-0px!">
            <el-input v-model="row.per100g" placeholder="请输入每100g含量" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="每100ml含量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.per100ml`" :rules="formRules.per100ml" class="mb-0px!">
            <el-input v-model="row.per100ml" placeholder="请输入每100ml含量" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="每100kj含量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.per100kj`" :rules="formRules.per100kj" class="mb-0px!">
            <el-input v-model="row.per100kj" placeholder="请输入每100kj含量" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unit`" :rules="formRules.unit" class="mb-0px!">
            <el-input v-model="row.unit" placeholder="请输入排序" readonly/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="排序" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.sort`" :rules="formRules.sort" class="mb-0px!">
            <el-input v-model="row.sort" placeholder="请输入排序" readonly/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加奶粉营养成分</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import SelectMilkAttributeCom from "@/views/aib/milkattribute/components/SelectMilkAttributeCom.vue";
import { MilkApi } from '@/api/aib/milk'
import * as events from "events";

const props = defineProps<{
  milkId: undefined // 奶粉（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  milkId: [{ required: true, message: '奶粉不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '营养成分不能为空', trigger: 'change' }],
  unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.milkId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await MilkApi.getMilkNutrientsListByMilkId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    milkId: undefined,
    name: undefined,
    type: undefined,
    per100g: undefined,
    per100ml: undefined,
    per100kj: undefined,
    unit: undefined,
    sort: undefined,
  }
  row.milkId = props.milkId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 监听 选择营养成分 的事件*/
const onSelectAttribute = (data, row) => {
  if (formData.value.some((item) => item.name === data.name && item.sort !== undefined)) {
    row.name = undefined;
    ElMessage.error('该营养成分已存在，请重新选择')
    return;
  }
  row.type = data.type;
  row.unit = data.unit;
  row.sort = data.sort;
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

defineExpose({ validate, getData })
</script>
